package IOTest;

import java.io.RandomAccessFile;

public class RandomAccessFileTest {
    public static void main(String[] args) {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("randomAccessFile.dat", "rw");
            raf.write("刘刚".getBytes());
            raf.writeInt(23);
            raf.writeBoolean(true);
            raf.writeDouble(23.23);
            raf.writeChar('A');
            raf.writeUTF("UTF-8");
            raf.seek(0); // 将指针移动到文件的开头
            raf.write("李四".getBytes());
            // 会覆盖原有的数据，因为指针已经移动到了文件的开头。
            // 如果需要实现插入效果，需要将指针移动到插入位置，然后将插入位置后的数据读取出来，然后写入插入数据，再写入读取出来的数据。
            System.out.println("raf.getFilePointer() = " + raf.getFilePointer()); // 获取指针的位置
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        RandomAccessFile raf2 = null;
        try {
            raf2 = new RandomAccessFile("randomAccessFile.dat", "r");
            byte[] b = new byte[6];
            raf2.read(b);
            System.out.println(new String(b));
            System.out.println(raf2.readInt());
            System.out.println(raf2.readBoolean());
            System.out.println(raf2.readDouble());
            System.out.println(raf2.readChar());
            System.out.println(raf2.readUTF());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf2 != null) {
                try {
                    raf2.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
